package com.icloud.common.web.util;

import cn.hutool.core.util.StrUtil;
import com.icloud.common.web.dto.CommonLanguageDto;
import com.icloud.common.web.enums.LanguageSupportEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ObjectUtil {

    /**
     * 获取属性中为空的字段
     */
    public static String[] getNullField(Object target) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(target);
        PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
        Set<String> emptyFieldSet = new HashSet<>();
        for (PropertyDescriptor p : propertyDescriptors) {
            String name = p.getName();
            Object value = beanWrapper.getPropertyValue(name);
            if (value instanceof String) {
                if (StringUtils.isEmpty(value.toString())) {
                    emptyFieldSet.add(name);
                }
            } else {
                if (Objects.isNull(value)) {
                    emptyFieldSet.add(name);
                }
            }
        }
        String[] notNullField = new String[emptyFieldSet.size()];
        return emptyFieldSet.toArray(notNullField);
    }

    /**
     * 检测多语言入参参数
     */
    public static Boolean validateLanguageParam(List<CommonLanguageDto> languageDtoList) {
        //传递的参数
        Map<String, String> paramMap = languageDtoList.stream().collect(Collectors.toMap(CommonLanguageDto::getLang, CommonLanguageDto::getValue));
        //根据系统设定的语种枚举进行校验
        boolean result = true;
        for (LanguageSupportEnum languageSupportEnum : LanguageSupportEnum.values()) {
            //如果没有传递对应的语种，校验失败
            if(! paramMap.containsKey(languageSupportEnum.getLang())) {
                result = false;
                break;
            }
            //如果语种对应的内容为必填，校验参数值是否为空
            if(languageSupportEnum.getIsMust() && StrUtil.isEmpty(paramMap.get(languageSupportEnum.getLang()))) {
                result = false;
                break;
            }
        }
        return result;
    }
}
